package indi.jp.project.base.controller;

import indi.jp.project.base.entity.Employee;
import indi.jp.project.base.entity.EmployeeTemp;
import indi.jp.project.base.service.EmployeeService;
import indi.jp.project.base.thread.EmployeeThread;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.util.SimpleEntityUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bas/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/queryGrid")
    @ResponseBody
    public JsonResult queryGrid(@ModelAttribute Employee entity, HttpServletRequest request) {
        SimpleEntityUtil<Employee> simpleEntityUtil = new SimpleEntityUtil<>();
        entity = simpleEntityUtil.setBaseEntity(entity, request);
        try {
            Map<String, Object> map = employeeService.queryGrid(entity);
            return JsonResult.success(map);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(@RequestBody Employee entity, HttpServletRequest request) {
        SimpleEntityUtil<Employee> simpleEntityUtil = new SimpleEntityUtil<>();
        entity = simpleEntityUtil.setBaseEntity(entity, request);
        try {
            return employeeService.save(entity);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/deleteById")
    @ResponseBody
    public JsonResult deleteById(HttpServletRequest request) {
        String id = request.getParameter("id");
        try {
            int effectRow = employeeService.deleteById(id);
            if (effectRow > 0) {
                return JsonResult.success("");
            } else {
                return JsonResult.failure("未能成功删除，请刷新查看数据是否存在");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @GetMapping("/queryEmployeeDetail")
    @ResponseBody
    public JsonResult queryEmployeeDetail(HttpServletRequest request) {
        String id = request.getParameter("id");
        try {
            Employee entity = employeeService.findEmployeeById(id);
            if (entity != null) {
                return JsonResult.success(entity);
            } else {
                return JsonResult.failure("获取人员信息失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/importExcel")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return JsonResult.failure("请选择文件");
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (!".xls".equals(suffix) && !".xlsx".equals(suffix)) {
            return JsonResult.failure("错误的文件格式");
        }
        String username = request.getParameter("account");
        try {
            InputStream in = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(in);
            in.close();
            Sheet sheet = workbook.getSheetAt(0);
            int rowLength = sheet.getPhysicalNumberOfRows();
            System.out.println("总行数有多少行" + rowLength);
            Row row = null;
            // 工号
            Cell cell1 = null;
            // 姓名
            Cell cell2 = null;
            // 部门编码
            Cell cell3 = null;
            // 人员类型
            Cell cell4 = null;
            // 性别
            Cell cell5 = null;
            // 电话
            Cell cell6 = null;
            List<EmployeeTemp> list = new LinkedList<>();

            for (int i = 1; i < rowLength; i++) {
                row = sheet.getRow(i);
                cell1 = row.getCell(0);
                cell2 = row.getCell(1);
                cell3 = row.getCell(2);
                cell4 = row.getCell(3);
                cell5 = row.getCell(4);
                cell6 = row.getCell(5);
                if (cell1 != null && cell2 != null && cell3 != null && cell4 != null) {
                    cell1.setCellType(CellType.STRING);
                    String employeeNo = cell1.getStringCellValue().trim();
                    cell2.setCellType(CellType.STRING);
                    String name = cell2.getStringCellValue().trim();
                    cell3.setCellType(CellType.STRING);
                    String departmentCode = cell3.getStringCellValue().trim();
                    cell4.setCellType(CellType.STRING);
                    String kindCode = cell4.getStringCellValue().trim();
                    int gender = 1;
                    if (cell5 != null) {
                        cell5.setCellType(CellType.STRING);
                        gender = Integer.parseInt(cell5.getStringCellValue().trim());
                    }
                    String phone = "";
                    if (cell6 != null) {
                        cell6.setCellType(CellType.STRING);
                        phone = cell6.getStringCellValue().trim();
                    }
                    EmployeeTemp entity = new EmployeeTemp();
                    entity.setEmployeeNo(employeeNo);
                    entity.setName(name);
                    entity.setDepartmentCode(departmentCode);
                    entity.setKindCode(kindCode);
                    entity.setGender(gender);
                    entity.setPhone(phone);
                    entity.setCreateBy(username);
                    list.add(entity);
                }
            }
            employeeService.batchInsertTemp(list);
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/doExecute")
    @ResponseBody
    public JsonResult doExecute(HttpServletRequest request){
        if(EmployeeThread.IS_RUNNING){
           return JsonResult.failure("正在处理数据，请勿重复操作");
        } else {
            EmployeeThread thread = new EmployeeThread();
            new Thread(thread).start();
            return JsonResult.success("");
        }
    }

    @GetMapping("/queryTempGrid")
    @ResponseBody
    public JsonResult queryTempGrid(@ModelAttribute EmployeeTemp entity, HttpServletRequest request) {
        SimpleEntityUtil<EmployeeTemp> simpleEntityUtil = new SimpleEntityUtil<>();
        entity = simpleEntityUtil.setBaseEntity(entity, request);
        try {
            Map<String, Object> map = employeeService.queryTempGrid(entity);
            return JsonResult.success(map);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @GetMapping("/getEmployeeInfo")
    @ResponseBody
    public JsonResult getEmployeeInfo(HttpServletRequest request) {
        Employee entity = new Employee();
        String username = request.getParameter("account");
        entity.setUsername(username);
        try {
            Employee employee = employeeService.getEmployeeInfo(entity);
            return JsonResult.success(employee);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @GetMapping("/getProcessEmployee")
    public JsonResult getProcessEmployee(HttpServletRequest request) {
        String employeeNo = request.getParameter("employeeNo");
        String name = request.getParameter("name");
        String departmentName = request.getParameter("departmentName");
        String roleCode = request.getParameter("roleCode");
        String departmentCode = request.getParameter("departmentCode");
        String pageStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("pageSize");

        if("".equals(roleCode)){
            return JsonResult.failure("缺少角色编码");
        }
        if(pageStr == null || "".equals(pageStr) || pageSizeStr == null || "".equals(pageSizeStr)){
            return JsonResult.failure("缺少分页参数");
        }
        int page = Integer.parseInt(pageStr);
        int pageSize = Integer.parseInt(pageSizeStr);
        int offset = (page - 1) * pageSize;
        Map<String, Object> params = new HashMap<>();
        params.put("employeeNo", employeeNo);
        params.put("name", name);
        params.put("departmentName", departmentName);
        params.put("roleCode", roleCode);
        params.put("departmentCode", departmentCode);
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        try {
            Map<String, Object> map = employeeService.getProcessEmployee(params);
            return JsonResult.success(map);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

}
